#ifndef __UDP_SERVER_HPP__
#define __UDP_SERVER_HPP__
#include <iostream>
#include <string>
#include <memory>
#include <cstring>
#include <cerrno>
#include <functional>
#include "Mutex.h"
#include "Log.h"
#include "Initadd.h"
#include "ThreadPool.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace LogMudule;
using namespace ThreadPoolMoudle;

const static int gsockfd = -1;
// const static std::string gdefaultip = "127.0.0.1"; // 表示本地主机
const static uint16_t gdefaultport = 8080;
using adduser_t = std::function<void(IntAddr &id)>;
using remove_t = std::function<void(IntAddr &id)>;

using task_t = std::function<void()>;
using route_t = std::function<void(int sockfd, const std::string &message)>;

#define Die(code)   \
    do              \
    {               \
        exit(code); \
    } while (0)
#define CONV(v) (struct sockaddr *)(v)

class nocopy
{
public:
    nocopy() {}
    nocopy(const nocopy &) = delete;
    const nocopy &operator=(const nocopy &) = delete;
    ~nocopy() {}
};

class UdpServe : public nocopy
{

public:
    UdpServe(uint16_t potr = gdefaultport)
        : _sockfd(gsockfd), _addr(potr), _isrunning(false)
    {
    }
    void InitServe()
    {
        // 1.创建sockfd
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket" << strerror(errno);
            Die(1);
        }
        LOG(LogLevel::INFO) << "socket success,socket is" << _sockfd;
        // 2. 填充网络信息，并bind绑定
        // 2.1 有没有把socket信息，设置进入内核中？？没有，只是填充了结构体！
        // struct sockaddr_in local;
        // bzero(&local, sizeof(local));
        // local.sin_family = AF_INET;
        // local.sin_port = ::htons(_potr);
        // local.sin_addr.s_addr = ::inet_addr(_ip.c_str());

        // 2.2bind 设置进入内核环境
        int n = ::bind(_sockfd, _addr.NetAddr(), _addr.Netaddrlen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind" << strerror(errno);
            Die(2);
        }
        LOG(LogLevel::INFO) << "bind success";
    }
    void RegisterService(adduser_t adduser, route_t route, remove_t removeuser)
    {
        _adduser = adduser;
        _route = route;
        _removeuser = removeuser;
    }
    void Start()
    {
        _isrunning = true;
        while (1)
        {
            char inbuffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = ::recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, CONV(&peer), &len);
            if (n > 0)
            {
                IntAddr cli(peer);
                inbuffer[n] = 0;
                // std::string clientinfo = cli.Ip() + ":" + std::to_string(cli.Port()) + " # " + inbuffer;
                // // LOG(LogLevel::INFO) << "client say@" << inbuffer;
                // LOG(LogLevel::DEBUG) << clientinfo;
                // std::string echo_string = "echo#";
                // echo_string += inbuffer;
                // ::sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, CONV(&peer), sizeof(peer));

                std::string message;
                if (strcmp(inbuffer, "QUIT") == 0)
                {
                    _removeuser(cli);
                    message = cli.Addr() + "#" + "我走了你们聊";
                }
                else
                {
                    _adduser(cli);
                    message = cli.Addr() + "#" + inbuffer;
                }
                task_t task = std::bind(UdpServe::_route, _sockfd, message);
                ThreadPool<task_t>::GetInstance()->Equeue(task);
            }
        }
        _isrunning = false;
    }
    ~UdpServe()
    {
        if (_sockfd > gsockfd)
            ::close(_sockfd);
    }

private:
    int _sockfd;
    // uint16_t _potr;
    // std::string _ip;
    IntAddr _addr;
    adduser_t _adduser;
    remove_t _removeuser;
    route_t _route;
    bool _isrunning;
};

#endif